package com.mccken.practice.top100.Top_30$.Top_39;

import java.util.LinkedList;
import java.util.Queue;

import cn.hutool.core.util.StrUtil;

class TreeNode {
	int val;
	TreeNode left;
	TreeNode right;

	TreeNode(int val) {
		this.val = val;
	}
}

public class LevelOrderTraversal {

	public static void levelOrderPrint(TreeNode root) {
		if (root == null) {
			return;
		}

		Queue<TreeNode> queue = new LinkedList<>(); // 创建一个队列用于层次遍历  
		queue.offer(root); // 将根节点入队  

		StringBuffer sb = new StringBuffer();
		while (!queue.isEmpty()) {
			TreeNode currentNode = queue.poll(); // 出队并访问当前节点  
			if (currentNode != null) {
				sb.append(currentNode.val).append(",");
				if (currentNode.left == null && currentNode.right == null) {
					continue;
				}
				if (currentNode.left != null) {
					queue.offer(currentNode.left); // 左子节点入队  
				} else {
					queue.offer(null); // 空节点用null占位，以保持层次结构  
				}
				if (currentNode.right != null) {
					queue.offer(currentNode.right); // 右子节点入队  
				} else {
					queue.offer(null); // 空节点用null占位  
				}
			} else {
				sb.append("null,");
			}

		}
		String str = sb.toString();
		System.out.println(StrUtil.removeSuffix(str, ","));
	}

}